<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visible"
    :title="id ? '编辑' : '新增'"
    @close="resetForm"
    width="40%"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-form-item prop="appName" label="应用名称">
            <el-input v-model="formData.appName" placeholder="请输入应用名称" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="默认菜单">
            <el-tree
              ref="treeRef"
              class="filter-tree mt-2 tree-width"
              :data="treeData"
              node-key="_id"
              :props="{ label: 'name' }"
              default-expand-all
              show-checkbox
              check-on-click-node
              :expand-on-click-node="false"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="submitBtnLoading" @click="handleCreate">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { appInfo, appSave } from '@/api/system/appManagement'
import { findTree } from '@/api/system/menu'
import { ElMessage } from 'element-plus'
import { onMounted, watch } from 'vue'
const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  visible: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['update:visible', 'create', 'update'])
const formRef = ref()
const submitBtnLoading = ref(false)
const treeRef = ref(null)
const treeData = ref([])
const formData = reactive({
  appName: ''
})
const formRules = reactive({
  appName: [{ required: true, trigger: 'blur', message: '请输入应用名称！' }]
})
const resetForm = () => {
  formRef.value?.resetFields()
  emit('update:visible')
  delete formData._id
  delete formData.menuIdList
}
const handleCreate = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      submitBtnLoading.value = true
      formData.menuIdList = [...treeRef.value.getCheckedKeys(), ...treeRef.value.getHalfCheckedKeys()]
      appSave(formData)
        .then((res) => {
          ElMessage.success('操作成功')
          emit('create')
          resetForm()
        })
        .finally(() => {
          submitBtnLoading.value = false
        })
    }
  })
}
watch(
  () => props.visible,
  (newValue) => {
    if (newValue && props.id) {
      appInfo(props.id).then((res) => {
        Object.assign(formData, res.data)
        treeRef.value.setCheckedKeys(res.data.menuIdList)
      })
    }
  }
)
onMounted(() => {
  findTree().then((res) => {
    treeData.value = res.data
  })
})
</script>

<style lang="scss" scoped></style>
